//
//  TestAudioController.m
//  ProjectDemo
//
//  Created by IOS3 on 2018/11/14.
//  Copyright © 2018 IOS3. All rights reserved.
//
/*
 {
 "data": [
 {
 "id": 43,
 "title": "Old Memory",
 "artist": "三輪学",
 "pic": "http://aufree.qiniudn.com/images/album/img20/89520/4280541424067346.jpg",
 "music_url" : "http://aufree.qiniudn.com/1770059653_2050944_l.mp3",
 "file_name" : "1770059653_2050944_l",
 "content": "此曲旋律轻快, 美妙, 仿佛欲将人带入一个十分干净且祥和的小镇... "
 },
 {
 "id": 2,
 "title": "A Little Story",
 "artist": "Valentin",
 "pic": "http://aufree.qiniudn.com/images/album/img28/65928/4263201298258620.jpg",
 "music_url" : "http://aufree.qiniudn.com/1770040300_2031329_l.mp3",
 "file_name" : "1770040300_2031329_l",
 "content": "整首歌曲曲调轻松欢快, 这几天一直循环播放~"
 },
 {
 "id": 111,
 "title": "letter song",
 "artist": "ヲタみん",
 "pic": "http://aufree.qiniudn.com/images/album/img75/87975/6615037721361503772.jpg",
 "music_url" : "http://aufree.qiniudn.com/1771694697_4194836_l.mp3",
 "file_name" : "1771694697_4194836_l",
 "content": "致十年后的自己，人生能有几个十年"
 }
 ]
 }

 */

#import "TestAudioController.h"
#import <FSAudioStream.h>



@interface TestAudioController ()<FSPCMAudioStreamDelegate>

@property (weak, nonatomic) IBOutlet UILabel *lable1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (weak, nonatomic) IBOutlet UILabel *label3;
@property (weak, nonatomic) IBOutlet UISlider *slider;

@property (nonatomic, strong) FSAudioStream *audioStream;
@property (nonatomic, strong) NSTimer *playerTimer;
@property (nonatomic, assign) float playbackTime;

@end

@implementation TestAudioController

- (void)viewDidLoad {
    [super viewDidLoad];
 
    [self initialFSAudioStream];
}

- (void)initialFSAudioStream {
    self.audioStream = FSAudioStream.new;
    self.audioStream.delegate = self;
    
    
    // 播放失败的回调
    self.audioStream.onFailure = ^(FSAudioStreamError error, NSString *errorDescription) {
        DLog(@"FS播放失败 %@", errorDescription);
    };
    
    // 播放完成的回调
    self.audioStream.onCompletion = ^{
        DLog(@"FS 播放完成");
    };
    
    // FreeStreamAudio 的转态回调
    self.audioStream.onStateChange = ^(FSAudioStreamState state) {
        
    };
    
    // 设置音量
//    [self.audioStream setVolume:0.5];
    
    // 出现 Strict content type checking active, application/octet-stream is not an audio content type 错误, 是错误类型
    // 设置不检测格式
//    self.audioStream.strictContentTypeChecking = NO;
//    self.audioStream.defaultContentType = @"audio/mpeg";
    
    // 设置播放音频
//    NSURL *url = [NSURL URLWithString:@"http://mr1.doubanio.com/f2b04c69eb8d93e3de4748e50e11600e/0/fm/song/p453_128k.mp4"];
    NSURL *url = [NSURL fileURLWithPath:[NSBundle.mainBundle pathForResource:@"秋意浓" ofType:@"mp3"]];
    [self.audioStream playFromURL:url];
    
    self.playerTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(playProgressAction) userInfo:nil repeats:YES];
    
}


// fmod 取模 floor 取整
- (void)playProgressAction {
    FSStreamPosition position = self.audioStream.currentTimePlayed;

    self.playbackTime = position.playbackTimeInSeconds/1;
    double minutesElapsed =floor(fmod(self.playbackTime/60.0,60.0));
    double secondsElapsed =floor(fmod(self.playbackTime,60.0));
    
    // DLog(@"playbackTime: %f", self.playbackTime);
    self.lable1.text = [NSString stringWithFormat:@"播放: %02.0f:%02.0f",minutesElapsed, secondsElapsed];
    self.slider.value = position.position;//播放进度

    // 总时长
    // float totalTime = position.playbackTimeInSeconds / position.position;
    // self.label2.text = [NSString stringWithFormat:@"总时长: %f", totalTime];
    
    // 剩余总时长
    float residualTime = position.playbackTimeInSeconds / position.position - position.playbackTimeInSeconds;
    float residualMinutes = floor(fmod(residualTime / 60.0, 60.0));
    float residualSeconds = floorf(fmod(residualTime, 60.0));
    NSString *residualStr = [NSString stringWithFormat:@"%02.0f:%02.0f", residualMinutes, residualSeconds];
    if ([residualStr isEqualToString:@"nan:nan"]) {
        residualStr = @"00:00";
    }
    self.label2.text = [NSString stringWithFormat:@"剩余: %@", residualStr];
}



#pragma mark - FS 代理
- (void)audioStream:(FSAudioStream *)audioStream samplesAvailable:(AudioBufferList *)samples frames:(UInt32)frames description: (AudioStreamPacketDescription)description {

//    DLog(@"frames: %d", frames);
//
//    DLog(@"description.mStartOffset: %lld", description.mStartOffset);
//    DLog(@"description.mVariableFramesInPacket: %d", description.mVariableFramesInPacket);
//    DLog(@"description.mDataByteSize: %d", description.mDataByteSize);
    
}



#pragma mark - button click

// paus 方法暂停播放, play方法是初始化后开始播放
- (IBAction)playButtonClick:(UIButton *)sender {
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(playPaus) object:nil];
    [self performSelector:@selector(playPaus) withObject:nil afterDelay:0.2];
}
- (IBAction)pausButtonClick:(UIButton *)sender {
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(playPaus) object:nil];
    [self performSelector:@selector(playPaus) withObject:nil afterDelay:0.2];
}
- (IBAction)lastButtonClick:(UIButton *)sender {
    [self.audioStream stop];
    NSURL *url = [NSURL fileURLWithPath:[NSBundle.mainBundle pathForResource:@"一路上有你" ofType:@"mp3"]];
    [self.audioStream playFromURL:url];
}
- (IBAction)nextButtonClick:(UIButton *)sender {
    [self.audioStream stop];
    NSURL *url = [NSURL fileURLWithPath:[NSBundle.mainBundle pathForResource:@"一千个伤心的理由" ofType:@"mp3"]];
    [self.audioStream playFromURL:url];
}
- (IBAction)advanceButtonClick:(UIButton *)sender {
    
}
- (IBAction)backButtonClick:(UIButton *)sender {
}
- (IBAction)sliderChanged:(UISlider *)sender {
    DLog(@"%f", sender.value);
    if (sender.value == 1) {
        [self nextButtonClick:nil];
    }
    else if (sender.value >= 0) {
        FSStreamPosition position = {0};
        position.position = sender.value;
        [self.audioStream seekToPosition:position];
    }
}




- (void)playPaus {
    if (self.audioStream.isPlaying) {
        [self.audioStream pause];
        [self.playerTimer setFireDate:[NSDate distantFuture]];
    }
    else {
        [self.audioStream pause];
        [self.playerTimer setFireDate:[NSDate distantPast]];
    }
}
@end
